package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ZipUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ZipAdapter;
import flc.ast.bean.MyZipBean;
import flc.ast.databinding.ActivityFileZipBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.UriUtil;

public class FileZipActivity extends BaseAc<ActivityFileZipBinding> {

    public static boolean isZip = false;
    private int itemPos = -1;//当前正在处理的item
    private boolean isCompCom = true;//是否已经完成压缩
    private ZipAdapter zipAdapter;
    private List<MyZipBean> listZip = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_file_zip;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFileZipBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mDataBinding.ivFileZipStart.setOnClickListener(this);

        mDataBinding.rvZipList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        zipAdapter = new ZipAdapter();
        mDataBinding.rvZipList.setAdapter(zipAdapter);
        zipAdapter.addChildClickViewIds(R.id.ivZipItemDel);
        zipAdapter.setOnItemChildClickListener(this);
        zipAdapter.setOnItemClickListener(this);
        zipAdapter.setZip(isZip);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivFileZipStart://上传文件
                getPermission();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivZipItemDel://删除
                listZip.remove(position);
                zipAdapter.setList(listZip);
                zipAdapter.notifyDataSetChanged();
                itemPos = listZip.size() - 1;
                if (listZip.size() == 0) {
                    itemPos = -1;
                    mDataBinding.tvFileZipNoData.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        if (isZip) {
            mDataBinding.tvFileZipTitle.setText(R.string.file_compress);
            mDataBinding.ivFileZipStart.setImageResource(R.drawable.ashangchuanwj);
        } else {
            mDataBinding.tvFileZipTitle.setText(R.string.file_decompression);
            mDataBinding.ivFileZipStart.setImageResource(R.drawable.awenjianjy);
        }
    }

    //压缩文件
    private void compress(String path) {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                boolean isComp = false;
                String resultFile = FileUtil.generateFilePath(Content.MyZip, ".zip");
                try {
                    isComp = ZipUtils.zipFile(path, resultFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                emitter.onNext(isComp);
            }

            @Override
            public void accept(Boolean isSuc) {
                zipAdapter.getItem(itemPos).setProgress(getRandom(90, 60));
                zipAdapter.notifyItemChanged(itemPos);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        zipAdapter.getItem(itemPos).setProgress(100);
                        zipAdapter.notifyItemChanged(itemPos);
                        if (itemPos < zipAdapter.getValidData().size() - 1) {
                            //继续压缩下一个
                            isCompCom = false;
                            itemPos++;
                            compress(zipAdapter.getItem(itemPos).getPath());
                        } else {
                            //压缩完成
                            isCompCom = true;
                        }
                    }
                }, 1000);
            }
        });
    }

    //解压文件
    private void disCompress(String path) {
        String disPath = PathUtils.getFilesPathExternalFirst()
                + Content.MyUnZip + "/" + FileUtils.getFileNameNoExtension(path);
        File fileByPath = FileUtils.getFileByPath(path);
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                try {
                    ZipUtils.unzipFile(fileByPath.getPath(), disPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                emitter.onNext("");
            }

            @Override
            public void accept(String directory) {
                zipAdapter.getItem(itemPos).setProgress(getRandom(90, 60));
                zipAdapter.notifyItemChanged(itemPos);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        zipAdapter.getItem(itemPos).setProgress(100);
                        zipAdapter.notifyItemChanged(itemPos);
                        if (itemPos < zipAdapter.getValidData().size() - 1) {
                            //继续解压下一个
                            isCompCom = false;
                            itemPos++;
                            disCompress(zipAdapter.getItem(itemPos).getPath());
                        } else {
                            //解压完成
                            isCompCom = true;
                        }
                    }
                }, 1000);
            }
        });
    }

    //生成区间内随机数
    private int getRandom(int maxNum, int minNum) {
        Random random = new Random();
        int i = random.nextInt(maxNum) % (maxNum - minNum + 1) + minNum;
        return i;
    }

    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_compress_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                try {
                    startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), Content.FILE_SELECT_AGAIN_CODE);
                } catch (android.content.ActivityNotFoundException ex) {
                }
            }
        }).request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.FILE_SELECT_AGAIN_CODE) {
            Uri audioUri = data.getData();
            if (audioUri == null) {
                return;
            }
            String filePath = UriUtil.uri2File(audioUri).getPath();
            if (filePath == null || TextUtils.isEmpty(filePath)) return;
            mDataBinding.tvFileZipNoData.setVisibility(View.GONE);
            listZip.add(new MyZipBean(FileUtils.getFileName(filePath), FileUtils.getSize(filePath)
                    , filePath, getRandom(50, 20)));
            zipAdapter.setList(listZip);
            if (isCompCom) {
                isCompCom = false;
                itemPos++;
                //如果已经完成压缩/解压，则继续启动压缩/解压
                if (isZip) {
                    compress(filePath);
                } else {
                    disCompress(filePath);
                }
            }
        }
    }

}